package com.example.hoyn.uartkitforas;

import java.util.Arrays;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.iflytek.aiui.uartkit.UARTAgent;
import com.iflytek.aiui.uartkit.constant.UARTConstant;
import com.iflytek.aiui.uartkit.entity.AIUIPacket;
import com.iflytek.aiui.uartkit.entity.CustomPacket;
import com.iflytek.aiui.uartkit.entity.MsgPacket;
import com.iflytek.aiui.uartkit.listener.EventListener;
import com.iflytek.aiui.uartkit.listener.UARTEvent;

public class MainActivity extends Activity {
	private static final String TAG = "UART_Controller";
	private EditText edittext;
	
	UARTAgent mAgent;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		edittext = (EditText) findViewById(R.id.editText);
		findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				mAgent = UARTAgent.createAgent(edittext.getText().toString(), 115200, new EventListener() {

					@Override
					public void onEvent(UARTEvent event) {
						switch (event.eventType) {
							case UARTConstant.EVENT_INIT_SUCCESS:
								showToast("Init UART Success");
								Log.e(TAG, "Init UART Success");
								break;

							case UARTConstant.EVENT_INIT_FAILED:
								showToast("Init UART Failed");
								Log.e(TAG, "Init UART Failed ");
								break;

							case UARTConstant.EVENT_MSG:
								MsgPacket recvPacket = (MsgPacket) event.data;
								processPacket(recvPacket);
								showToast("收到消息ID ： "+recvPacket.getSeqID());
								break;

							case UARTConstant.EVENT_SEND_FAILED:
								MsgPacket sendPacket = (MsgPacket) event.data;
								mAgent.sendMessage(sendPacket);
								showToast("发送消息失败,消息ID : "+sendPacket.getSeqID());
							default:
								break;
						}
					}
				});
			}
		});

	}

	private void processPacket(MsgPacket packet) {
		switch (packet.getMsgType()) {
		case MsgPacket.AIUI_PACKET_TYPE:
			showToast("recv aiui result" + new String(((AIUIPacket) packet).content));
			Log.e(TAG, "recv aiui result" + new String(((AIUIPacket) packet).content));
			break;
		case MsgPacket.CUSTOM_PACKET_TYPE:
			showToast("recv aiui custom data " + Arrays.toString(((CustomPacket)packet).customData));
			Log.e(TAG, "recv aiui custom data " + Arrays.toString(((CustomPacket)packet).customData));
			break;
		default:
			break;
		}
	}
	private void showToast(final String msg){
		runOnUiThread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
			}
		});
	}
	
	
}
